package com.joyd.joydlib.io

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okio.ByteString
import java.nio.charset.Charset

/**
 * WebSocket客户端使用示例
 * 
 * 这个类展示了如何在Android应用中使用WebSocketClient和WebSocketManager
 */
class WebSocketExampleActivity : AppCompatActivity() {
    private val TAG = "WebSocketExample"
    private lateinit var webSocketManager: WebSocketManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 初始化WebSocket管理器
        initWebSocketManager()
    }

    private fun initWebSocketManager() {
        // 创建WebSocket管理器实例
        webSocketManager = WebSocketManager()

        // 配置WebSocket管理器
        webSocketManager
            .setUrl("wss://example.com/ws") // 替换为实际的WebSocket服务器地址
            .setClientConfig(WebSocketManager.createDefaultClientBuilder())
            .setReconnectConfig(
                maxAttempts = 15,
                baseDelayMs = 1000L,
                maxDelayMs = 60000L
            )

        // 监听消息
        CoroutineScope(Dispatchers.Main).launch {
            webSocketManager.messageFlow.collect {
                handleTextMessage(it)
            }
        }

        // 监听二进制消息
        CoroutineScope(Dispatchers.Main).launch {
            webSocketManager.binaryMessageFlow.collect {
                handleBinaryMessage(it)
            }
        }

        // 监听连接状态变化
        CoroutineScope(Dispatchers.Main).launch {
            webSocketManager.stateFlow.collect {
                handleStateChange(it)
            }
        }

        // 监听错误
        CoroutineScope(Dispatchers.Main).launch {
            webSocketManager.errorFlow.collect {
                handleError(it)
            }
        }
    }

    /**
     * 连接WebSocket
     */
    fun connectWebSocket() {
        webSocketManager.connect()
    }

    /**
     * 断开WebSocket连接
     */
    fun disconnectWebSocket() {
        webSocketManager.disconnect()
    }

    /**
     * 暂停WebSocket连接
     */
    fun pauseWebSocket() {
        webSocketManager.pause()
    }

    /**
     * 恢复WebSocket连接
     */
    fun resumeWebSocket() {
        webSocketManager.resume()
    }

    /**
     * 发送文本消息
     */
    fun sendTextMessage(message: String) {
        val success = webSocketManager.sendMessage(message)
        if (success) {
            Log.d(TAG, "消息发送成功: $message")
        } else {
            Log.e(TAG, "消息发送失败: $message")
        }
    }

    /**
     * 发送二进制消息
     */
    fun sendBinaryMessage(data: ByteArray) {
        val byteString = ByteString.of(*data)
        val success = webSocketManager.sendBinaryMessage(byteString)
        if (success) {
            Log.d(TAG, "二进制消息发送成功")
        } else {
            Log.e(TAG, "二进制消息发送失败")
        }
    }

    /**
     * 处理接收到的文本消息
     */
    private fun handleTextMessage(message: String) {
        Log.d(TAG, "收到文本消息: $message")
        // 在这里处理接收到的文本消息
        // 例如更新UI、解析数据等
    }

    /**
     * 处理接收到的二进制消息
     */
    private fun handleBinaryMessage(byteString: ByteString) {
        val data = byteString.toByteArray()
        val text = String(data, Charset.defaultCharset())
        Log.d(TAG, "收到二进制消息 (长度: ${data.size} bytes): $text")
        // 在这里处理接收到的二进制消息
    }

    /**
     * 处理连接状态变化
     */
    private fun handleStateChange(state: WebSocketClient.ConnectionState) {
        when (state) {
            WebSocketClient.ConnectionState.Disconnected -> {
                Log.d(TAG, "WebSocket已断开连接")
                // 处理断开连接的逻辑
            }
            WebSocketClient.ConnectionState.Connecting -> {
                Log.d(TAG, "WebSocket正在连接...")
                // 处理连接中的逻辑
            }
            WebSocketClient.ConnectionState.Connected -> {
                Log.d(TAG, "WebSocket已连接成功")
                // 处理连接成功的逻辑
            }
            WebSocketClient.ConnectionState.Paused -> {
                Log.d(TAG, "WebSocket已暂停")
                // 处理暂停的逻辑
            }
        }
    }

    /**
     * 处理错误
     */
    private fun handleError(throwable: Throwable?) {
        Log.e(TAG, "WebSocket错误", throwable)
        // 在这里处理错误情况
    }

    /**
     * 清理资源
     */
    fun release() {
        // 释放WebSocket资源
        webSocketManager.release()
    }
}